<template>
  <div class="remind-add">
    <van-nav-bar title="添加提醒" left-text="返回" left-arrow @click-left="onClickLeft" />
    <van-form @submit="onSubmit">
      <van-cell-group inset>
        <van-field
          v-model="form.name"
          name="name"
          label="名称"
          placeholder="请输入提醒名称"
          :rules="[{ required: true, message: '请输入提醒名称' }]"
        />
        <van-field
          v-model="form.content"
          name="content"
          label="内容"
          placeholder="请输入内容"
          :rules="[{ required: false, message: '请填写内容' }]"
        />
        <van-field
          v-model="form.email"
          name="email"
          label="邮箱"
          placeholder="请输入提醒邮箱"
          :rules="[{ required: true, message: '请输入提醒邮箱' }]"
        />
        <van-field
          v-model="form.remindTime"
          name="remindTime"
          label="提醒时间"
          placeholder="请选择提醒时间"
          readonly
          @click="showPopup('date')"
        />
        <van-field
          v-model="form.remindType"
          name="remindType"
          label="提醒类型"
          placeholder="请选择提醒类型"
          :rules="[{ required: true, message: '请选择提醒类型' }]"
          readonly
          @click="showPopup('type')"
        />
        <van-field
          v-model="form.state"
          name="state"
          label="状态"
          autocomplete="off"
          placeholder="请输入状态"
          @click="showState"
          readonly
          :rules="[{ required: true, message: '请填写提醒状态' }]"
        />
      </van-cell-group>

      <div style="margin: 16px">
        <van-button round block type="primary" native-type="submit"> 保存 </van-button>
      </div>
    </van-form>

    <van-popup :show="showPopupVisible" position="bottom" round>
      <van-picker-group
        v-if="popupType === 'date'"
        title="选择提醒时间"
        :tabs="['选择日期', '选择时间']"
        next-step-text="下一步"
        @confirm="onDateConfirm"
        @cancel="showPopupVisible = false"
      >
        <van-date-picker v-model="currentDate" :min-date="minDate" />
        <van-time-picker v-model="currentTime" />
      </van-picker-group>
      <van-picker
        v-if="popupType === 'type'"
        v-model="currentType"
        :columns="typeColumns"
        title="选择提醒类型"
        @confirm="onTypeConfirm"
        @cancel="showPopupVisible = false"
      />
      <van-picker
        v-if="popupType === 'status'"
        v-model="currentStatus"
        :columns="statusColumns"
        title="选择状态"
        @confirm="onStatusConfirm"
        @cancel="showPopupVisible = false"
      />
    </van-popup>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'
import { addRemind } from '@/requests/remindItem'
import { getDictionary } from '@/requests/dictionary'

const router = useRouter()
const form = ref({
  name: '',
  email: '',
  remindTime: '',
  remindType: '',
  content: '',
  state: ''
})
const showPopupVisible = ref(false)
const popupType = ref('')
const minDate = new Date()
const typeColumns = ref([])
const statusColumns = ref([])
const currentDate = ref([new Date().getFullYear(), new Date().getMonth() + 1, new Date().getDate()])
const currentTime = ref([new Date().getHours(), new Date().getMinutes()])
const currentType = ref([])
const currentStatus = ref([])

onMounted(() => {
  // 设置默认的提醒时间
  form.value.remindTime = `${currentDate.value[0]}-${formatNumber(currentDate.value[1])}-${formatNumber(currentDate.value[2])} ${formatNumber(currentTime.value[0])}:${formatNumber(currentTime.value[1])}`

  getDictionary('REMIND_TYPE', data => {
    typeColumns.value = data
    console.log(typeColumns.value)
    if (typeColumns.value.length > 0) {
      currentType.value = [typeColumns.value[0]]
      form.value.remindType = typeColumns.value[0].value
    }
  })

  getDictionary('REMIND_STATE', data => {
    statusColumns.value = data
    console.log(statusColumns.value)
    if (statusColumns.value.length > 0) {
      currentStatus.value = [statusColumns.value[0]]
      form.value.state = statusColumns.value[0].value
    }
  })
})

const showPopup = type => {
  popupType.value = type
  showPopupVisible.value = true
}

const formatNumber = num => {
  return num < 10 ? `0${num}` : num
}

const onDateConfirm = () => {
  const [year, month, day] = currentDate.value
  const [hour, minute] = currentTime.value
  form.value.remindTime = `${year}-${month}-${day} ${hour}:${minute}`
  showPopupVisible.value = false
}

const onTypeConfirm = ({ selectedValues }) => {
  console.log(selectedValues)
  form.value.remindType = selectedValues[0]
  showPopupVisible.value = false
}

const onStatusConfirm = ({ selectedValues }) => {
  form.value.state = selectedValues[0]
  showPopupVisible.value = false
}

const showState = () => {
  popupType.value = 'status'
  showPopupVisible.value = true
}

const onClickLeft = () => {
  router.back()
}

const onSubmit = async () => {
  try {
    const res = await addRemind(form.value)
    if (res.code === 200) {
      showToast({
        type: 'success',
        message: '添加成功',
        duration: 1500
      })
      router.back()
    } else {
      showToast({
        type: 'fail',
        message: res.message || '添加失败',
        duration: 1500
      })
    }
  } catch (error) {
    showToast({
      type: 'fail',
      message: '网络错误，请稍后重试',
      duration: 1500
    })
  }
}
</script>

<style scoped lang="scss">
.remind-add {
  min-height: 100vh;
  background-color: #f7f8fa;
}
</style>
